/*
 * ucicmd - Api command for the Unified Configuration Interface
 * Copyright (C) 2009 Fabian Omar Franzotti <fofware@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 2.1
 * as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#include <uci_cmd.h>

int uci_do_cmd ( struct uci_context *ctx, int cmd, char *strTuple ) {
	struct uci_ptr ptr;
	char *running;
	struct uci_element *e;
	int ret = UCI_OK;
	char *param;
	int intSize;

	intSize = strlen(strTuple) +1;
	param = malloc(intSize);
	memset(param,0,intSize);
	sprintf(param,"%s", strTuple);
	running = param;

	if (uci_lookup_ptr(ctx, &ptr, running, true) != UCI_OK) {
		uci_perror(ctx, running);
		return 1;
	}

	switch(cmd) {
/*
	case CMD_GET:
		if (!(ptr.flags & UCI_LOOKUP_COMPLETE)) {
			ctx->err = UCI_ERR_NOTFOUND;
			cli_perror();
			return 1;
		}
		switch(e->type) {
		case UCI_TYPE_SECTION:
			printf("%s\n", ptr.s->type);
			break;
		case UCI_TYPE_OPTION:
			uci_show_value(ptr.o);
			break;
		default:
			break;
		}
		break;
*/
	case CMD_RENAME:
		ret = uci_rename(ctx, &ptr);
		break;
	case CMD_REVERT:
		if ( (ptr.target == 2 && !ptr.p) 
		|| (ptr.target == 3 && !ptr.s) 
		|| (ptr.target == 4 && !ptr.o) ) {
			return UCI_OK;
		}
		ret = uci_revert(ctx, &ptr);
		break;
	case CMD_SET:
		if ( ptr.target == 3 && ptr.s ) {
			return UCI_OK;
		}
		ret = uci_set(ctx, &ptr);
		break;
	case CMD_ADD_LIST:
		ret = uci_add_list(ctx, &ptr);
		break;
	case CMD_DEL:
		ret = uci_delete(ctx, &ptr);
		break;
	}

	if (ret != UCI_OK) {
		uci_perror(ctx, running);
	} else {
		ret = uci_save(ctx, ptr.p);
	}
	free(param);
	return ret;
}
